<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import { userAdd, userFind, userFindById, userModify, userRemove, userResetPassword } from '@/api/system/user'
import { Message, Modal } from '@arco-design/web-vue'
import { useGlobalStore } from '@/stores/global'
import { log } from 'node:util'

const globalStore = useGlobalStore()
// 搜索表单
const searchForm = reactive({
  // 显示控制
  visible: true,
  // 表单
  form: {
    email: '',
    nickName: ''
  },
  // 搜索
  search: () => {
    userFind(searchForm.form, {
      pageNum: searchForm.list.pageNum,
      pageSize: searchForm.list.pageSize
    }).then((resp: any) => {
      searchForm.list = resp.data
    })
  },
  // 重置
  reset: () => {
    searchForm.form = {
      email: '',
      nickName: ''
    }
    searchForm.reset()
  },
  // table 数据
  list: {
    list: [],
    total: 0,
    pageSize: 10,
    pageNum: 1
  }
})

// 操作数据表单
const operationForm = reactive({
  // 弹框标题
  title: '添加用户',
  // 是否显示
  visible: false,
  // 表单
  form: {
    id: null,
    age: 0,
    email: '',
    avatarUrl: '',
    nickName: '',
    password: '',
    qq: '',
    state: null,
    username: ''
  },
  // 验证
  rules: [
    {}
  ],
  reset: () => {
    operationForm.form = {
      id: null,
      age: 0,
      email: '',
      avatarUrl: '',
      nickName: '',
      password: '',
      qq: '',
      state: null,
      username: ''
    }
  },
  // 打开弹框
  open: () => {
    operationForm.title = '添加用户'
    operationForm.visible = true
    operationForm.reset()
  },
  modify: (record: any) => {
    operationForm.title = '修改用户'
    userFindById(record.id).then(resp => {
      operationForm.form = resp.data
      operationForm.visible = true
    })
  },
  remove: (record: any) => {
    Modal.confirm({
      title: '警告！',
      content: `是否确认删除 [${record.nickName}] 用户？`,
      onOk(e) {
        if (record.id == globalStore.global.userInfo.id) {
          Message.error('不能删除当前用户！！！')
          return
        }
        userRemove(record.id)
      }
    })
  },
  submit: ({ errors, values }: any) => {
    if (errors) return
    if (values.id) {
      userModify(operationForm.form).then(() => {
        operationForm.visible = false
        searchForm.search()
      })
      return
    }

    userAdd(values).then(() => {
      operationForm.visible = false
      searchForm.search()
    })
  },
  resetPassword: (record: any) => {
    Modal.confirm({
      title: '警告！',
      content: `确认重置 [${record.nickName}] 的密码吗？`,
      onOk(e) {
        userResetPassword(record.id)
      }
    })
  }
})


//头像上传
const file = ref()

const onChange = (_, currentFile: any) => {
  if (currentFile.response) {
    operationForm.form.avatarUrl = '/api' + currentFile.response.data
  }
  file.value = {
    ...currentFile
    // url: URL.createObjectURL(currentFile.file),
  }
}
const onProgress = (currentFile: any) => {
  console.log('进度变化', currentFile)
  file.value = currentFile
}

onMounted(() => {
  searchForm.search()
  document.title = 'Rocc管理系统 用户管理'
})

</script>

<template>
  <div class="w-full h-full">
    <a-form v-show="searchForm.visible">
      <a-row :gutter="10">
        <a-col :sm="12" :md="6">
          <a-form-item label="邮箱">
            <a-input v-model="searchForm.form.email" />
          </a-form-item>
        </a-col>
        <a-col :sm="12" :md="6">
          <a-form-item label="昵称">
            <a-input v-model="searchForm.form.nickName" />
          </a-form-item>
        </a-col>
        <a-col :span="5">
          <a-space>
            <a-button @click="searchForm.search">
              <template #icon>
                <icon-search />
              </template>
              搜索
            </a-button>
            <a-button @click="searchForm.reset">
              <template #icon>
                <icon-refresh />
              </template>
              重置
            </a-button>
          </a-space>
        </a-col>
      </a-row>
    </a-form>

    <div class="flex justify-between mr-1">
      <a-space wrap>
        <a-button type="primary" @click="operationForm.open">
          <template #icon>
            <icon-plus />
          </template>
          添加用户
        </a-button>
        <a-button>
          <template #icon>
            <icon-download />
          </template>
          导出用户
        </a-button>
      </a-space>
      <a-space>
        <a-tooltip content="刷新列表" @click="searchForm.search">
          <a-button size="small" shape="circle">
            <template #icon>
              <icon-refresh />
            </template>
          </a-button>
        </a-tooltip>
        <a-tooltip content="隐藏搜索" position="tr" @click="searchForm.visible = !searchForm.visible">
          <a-button size="small" shape="circle">
            <template #icon>
              <icon-search />
            </template>
          </a-button>
        </a-tooltip>
      </a-space>
    </div>
    <a-drawer v-model:visible="operationForm.visible" :title="operationForm.title" :width="500" :footer="false">
      <a-form ref="operationFormRef" :model="operationForm.form" @submit="operationForm.submit">
        <a-form-item label="头像">
          <a-upload
            action="/api/upload"
            :fileList="file ? [file] : []"
            :show-file-list="false"
            @change="onChange"
            @progress="onProgress"
          >
            <template #upload-button>
              <div
                :class="`arco-upload-list-item${
            file && file.status === 'error' ? ' arco-upload-list-item-error' : ''
          }`"
              >
                <div
                  class="arco-upload-list-picture custom-upload-avatar"
                  v-if="file && file.url"
                >
                  <img :src="file.url" />
                  <div class="arco-upload-list-picture-mask">
                    <IconEdit />
                  </div>
                  <a-progress
                    v-if="file.status === 'uploading' && file.percent < 100"
                    :percent="file.percent"
                    type="circle"
                    size="mini"
                    :style="{
                position: 'absolute',
                left: '50%',
                top: '50%',
                transform: 'translateX(-50%) translateY(-50%)',
              }"
                  />
                </div>
                <div class="arco-upload-picture-card" v-else>
                  <div class="arco-upload-picture-card-text">
                    <IconPlus />
                    <div style="margin-top: 10px; font-weight: 600">Upload</div>
                  </div>
                </div>
              </div>
            </template>
          </a-upload>
        </a-form-item>
        <a-form-item label="昵称" field="nickName">
          <a-input v-model="operationForm.form.nickName" />
        </a-form-item>
        <a-form-item label="用户名" field="username">
          <a-input v-model="operationForm.form.username" />
        </a-form-item>
        <a-form-item label="Email" field="email">
          <a-input v-model="operationForm.form.email" />
        </a-form-item>
        <a-form-item label="QQ" field="qq">
          <a-input v-model="operationForm.form.qq" />
        </a-form-item>
        <a-form-item label="状态" field="state">
          <a-select v-model="operationForm.form.state">
            <a-option :value="Number(k)" :label="v" v-for="(v,k) of globalStore.global.caches.commons.userState"
                      :key="k" />
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" html-type="submit">
            提交
          </a-button>
        </a-form-item>
      </a-form>
    </a-drawer>

    <a-table :data="searchForm.list.list" :pagination="false">
      <template #columns>
        <a-table-column title="ID" data-index="id"></a-table-column>
        <a-table-column title="昵称" data-index="nickName"></a-table-column>
        <a-table-column title="头像">
          <template #cell="{record}">
            <a-avatar :image-url="record.avatarUrl" />
          </template>
        </a-table-column>
        <a-table-column title="用户名" data-index="username"></a-table-column>
        <a-table-column title="状态" data-index="state">
          <template #cell="{record}">
            {{ globalStore.global.caches.commons.userState[record.state] }}
          </template>
        </a-table-column>
        <a-table-column title="最后登录时间" data-index="lastTime" width="180"></a-table-column>
        <a-table-column title="操作" width="160">
          <template #cell="{record}">
            <a-space>
              <a-button status="warning" @click="operationForm.modify(record)">
                <template #icon>
                  <icon-edit />
                </template>
                修改
              </a-button>
              <a-button status="warning" @click="operationForm.resetPassword(record)">
                <template #icon>
                  <icon-refresh />
                </template>
                重置密码
              </a-button>
              <a-button status="danger" @click="operationForm.remove(record)">
                <template #icon>
                  <icon-delete />
                </template>
                删除
              </a-button>
            </a-space>
          </template>
        </a-table-column>
      </template>
    </a-table>
    <div class="mt-4 flex justify-end">
      <a-pagination v-model:current="searchForm.list.pageNum"
                    v-model:page-size="searchForm.list.pageSize"
                    :total="searchForm.list.total"
                    @change="searchForm.search"
                    show-total
                    show-jumper
                    show-page-size
      ></a-pagination>
    </div>
  </div>
</template>

<style scoped>

</style>
